<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        function ajax(url, method, data, success, complete) {
            //IE7+, Firefox, Chrome, Opera, Safari使用new XMLHttpRequest()
            //IE6, IE5使用new ActiveXObject("Microsoft.XMLHTTP")
            var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            var sendData = '';

            //GET方式直接拼装url
            if (method.toUpperCase() === 'GET') {
                url += '?'
                for (var prop in data) {
                    url += (prop + '=' + data[prop] + '&');
                }
            //POST拼装在sendData中，由send（sendData）发送
            }else if(method.toUpperCase() === 'POST'){
                for (var prop in data) {
                    sendData += (prop + '=' + data[prop] + '&');
                }
            }
            xhr.open(method, url, true);
            //在onreadystatechange的事件函数中可以接收到返回信息
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 || xhr.status === 301) {
                        var res = {
                            status: xhr.status,
                            response: JSON.parse(xhr.response),
                            responseURL: xhr.responseURL,
                            statusText: xhr.statusText,
                        };
                        success(res);
                    } else {
                        var res = {
                            status: xhr.status,
                            responseURL: xhr.responseURL,
                            statusText: xhr.statusText,
                        };
                        complete(res);
                    }

                }
            };
            // POST必须设置请求头，且必须在open方法开启后才能设置
            method.toUpperCase() === 'POST' && xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            // 把send方法放在onreadystatechange之后，防止返回结果太快，导致onreadystatechange的事件未触发
            xhr.send(sendData);
            //本函数存在优化的地方，如jquery的fail的回调函数未封装，未考虑除301之外的重定向情况
            //如果你有更好的建议，请联系346551572@qq.com
        }

        //以下为使用方法
        var url = 'https://look.808b.com:3000/public/index.php/index/index/test';
        var method = 'POST';
        var data = {
            id: 1
        };
        ajax(url, method, data, function (res) {
            console.log(res);
        }, function (err) {
            console.log(err)
        })



    </script>

</body>

</html>